package com.xu.cloud.common.util;

import org.springframework.boot.env.PropertiesPropertySourceLoader;
import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.util.List;

/**
 * spring启动之前配置log4j2
 *
 * @author xuguan
 * @since 2024/1/18
 */
public class Log4j2LoadUtil {
    private static final String APPLICATION_YML = "application.yml";
    private static final String APPLICATION_PROPERTIES = "application.properties";

    public static void loadYaml() {
        openAnsi();

        // 读取application.yml配置文件
        addLog4j2SystemProperty(new YamlPropertySourceLoader(), APPLICATION_YML);
    }

    public static void loadProperties() {
        openAnsi();

        // 读取application.properties配置文件
        addLog4j2SystemProperty(new PropertiesPropertySourceLoader(), APPLICATION_PROPERTIES);
    }

    private static void openAnsi() {
        // 开启ANSI彩色日志
        System.setProperty("log4j.skipJansi", "false");
    }

    private static void addLog4j2SystemProperty(PropertySourceLoader loader, String applicationName) {
        String profile = null;

        List<PropertySource<?>> propertySources;
        try {
            propertySources = loader.load(applicationName, new ClassPathResource(applicationName));
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        for (PropertySource<?> propertySource : propertySources) {
            final Object property = propertySource.getProperty("spring.profiles.active");
            if (property != null) {
                profile = property.toString();
                break;
            }
        }

        if (profile != null) {
            System.setProperty("logging.config", "classpath:log4j2-" + profile + ".xml");
        }
    }
}
